package com.right.health.app.ui.registered;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.app.App;
import com.right.health.app.base.BasePresenterActivity;
import com.right.health.app.bean.FamilyResponse;
import com.right.health.app.constants.BroadCastCode;
import com.right.health.app.net.OrderApi;
import com.right.health.app.ui.registered.adapter.PatientAdapter;
import com.right.health.app.ui.registered.fragment.PayClinicFragment;
import com.vendor.social.utils.CollectionUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 诊间支付
 */
public class PayClinicActivity extends BasePresenterActivity implements OnHttpListener {

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private TextView mPatientTv;
    private View mCoverView;
    private PopupWindow mPopupWindow;
    private OrderApi mOrderApi;
    private List<PayClinicFragment> mFragments;
    private List<FamilyResponse.FamilyInfo> mPatients = new ArrayList<>();
    private PatientAdapter mPatientAdapter;
    private FamilyResponse.FamilyInfo mSelectPatient;
    private boolean mRequestSuccess;

    @Override
    public void onCreate(Bundle bundle, String s) {
        setContentView(R.layout.activity_pay_clinic);
    }

    @Override
    public void findView() {
        mTabLayout = findViewById(R.id.tb);
        mViewPager = findViewById(R.id.viewpager);
        mPatientTv = findViewById(R.id.tv_patient);
        mCoverView = findViewById(R.id.view_cover);
        mPatientTv.setOnClickListener(v -> {
            if (!mRequestSuccess) {
                mOrderApi.getPatientList();
            } else if (mPatients.size() > 1) {
                if (mPopupWindow == null) {
                    initPopupWindow();
                }
                showPopWindow(v);
            }
        });
        mFragments = new ArrayList<>();
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return mFragments.get(i);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return position == 0 ? "待支付" : "已支付";
            }
        });
        mTabLayout.setupWithViewPager(mViewPager);
        mSelectPatient = new FamilyResponse.FamilyInfo();
        mSelectPatient.memberid = App.getInstance().getUser().memberid;
        mSelectPatient.membername = "本人";
        mPatients.add(mSelectPatient);
        mPatientTv.setText(getString(R.string.format_current_patient, mSelectPatient.membername));
    }

    @Override
    public void initialize() {
        mOrderApi = new OrderApi();
        mOrderApi.setListener(this);
        mFragments.add(PayClinicFragment.newInstance("unPay", mSelectPatient.memberid));
        mFragments.add(PayClinicFragment.newInstance("paid", mSelectPatient.memberid));
        mViewPager.getAdapter().notifyDataSetChanged();
    }

    private void refreshFragmentDara() {
        mFragments.get(0).setPatientId(mSelectPatient.memberid);
        mFragments.get(1).setPatientId(mSelectPatient.memberid);
    }

    private void initPopupWindow() {
        View view;
        view = LayoutInflater.from(this).inflate(R.layout.layout_listview, null);
        ListView lvPopWindowList = view.findViewById(R.id.listView);
        lvPopWindowList.setVerticalScrollBarEnabled(false);
        mPatientAdapter = new PatientAdapter(this, mPatients.subList(1, mPatients.size()));
        lvPopWindowList.setAdapter(mPatientAdapter);
        lvPopWindowList.setOnItemClickListener((parent, view1, position, id) -> {
            if (mPopupWindow != null && mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            }
            mSelectPatient = mPatientAdapter.getItem(position);
            mPatientTv.setText(getString(R.string.format_current_patient, mSelectPatient.membername));
            refreshFragmentDara();
            List<FamilyResponse.FamilyInfo> adapterList = new ArrayList<>();
            adapterList.addAll(mPatients);
            adapterList.remove(mSelectPatient);
            mPatientAdapter.setDataSource(adapterList);
        });

        mPopupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);   //生成PopWindow
        mPopupWindow.setOnDismissListener(() -> {
//            darkenBackgroud(1f);
            mCoverView.setVisibility(View.GONE);
        });
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        mPopupWindow.setFocusable(true);
    }

    public void showPopWindow(View view) {
        mPopupWindow.showAsDropDown(view);
        mCoverView.setVisibility(View.VISIBLE);
//        darkenBackgroud(0.4f);
    }

    private void darkenBackgroud(Float bgcolor) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgcolor;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    @Override
    public void onResponse(Request request, Response response) {
        if (!response.isResponseFail()) {
            mRequestSuccess = true;
            FamilyResponse familyResponse = response.cast(FamilyResponse.class);
            if (familyResponse != null && !CollectionUtil.isEmpty(familyResponse.members)) {
                if (!CollectionUtil.isEmpty(familyResponse.members)) {
                    for (FamilyResponse.FamilyInfo info : familyResponse.members) {
                        if (TextUtils.equals(info.memberid, mSelectPatient.memberid)) {
                            mPatients.clear();
                            break;
                        }
                    }
                    mPatients.addAll(familyResponse.members);
                    initPopupWindow();
                    showPopWindow(mPatientTv);
                }
           /*     mSelectPatient = familyResponse.members.get(0);
                mPatientTv.setText(getString(R.string.format_current_patient, mSelectPatient.membername));
                mFragments.get(0).setPatientId(mSelectPatient.memberid);
                mFragments.get(1).setPatientId(mSelectPatient.memberid);*/

         /*       if (mPatients.size() == 1) {
                    mPatientTv.setCompoundDrawables(null, null, null, null);
                }*/
            }
        }
    }

    @Override
    public void onReceiveBroadcast(int intent, Bundle bundle) {
        super.onReceiveBroadcast(intent, bundle);
        if (intent == BroadCastCode.REFRESH_PAY_CLINIC_LIST && mSelectPatient != null) {
            refreshFragmentDara();
        }
    }
}
